package com.whsxt.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-03-12 10:55
 * @Description: token传递问题配置，远程调用的拦截
 */
@Configuration
public class OpenFeignInterceptor implements RequestInterceptor {


    /**
     * 在这里做token的传递
     * 1、浏览器请求--A服务--B服务      有token--有request
     * 2、mq直接发起远程调用             没有token---没有request
     * 3、支付宝回调  有request，但是没有token
     *
     * @param template 发起远程调用的请求
     */
    @Override
    public void apply(RequestTemplate template) {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            //有请求
            //1、浏览器请求
            //2、其他系统的回调  ：支付宝回调等
            HttpServletRequest request = requestAttributes.getRequest();
            if (!ObjectUtils.isEmpty(request)) {
                String authorization = request.getHeader("Authorization");
                if (!StringUtils.isEmpty(authorization)) {
                    //往新的请求里放，做一个传递
                    template.header("Authorization", authorization);
                    return;
                }
            }
        }

        //下面都是没有token的      包括mq和其他系统回调
        //设置一个永久token，保证可以正常调用其他服务
        template.header("Authorization", "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MTcxMDUxNTIsInVzZXJfbmFtZSI6Im9FZFF5NnFvS2tJZHVybWlBR1lYNGs5Y0lZSDgiLCJqdGkiOiIxOGZhM2RkNy0zOWY0LTRkZjAtYWEwYi1mYjgyZWFhZGZmOGUiLCJjbGllbnRfaWQiOiJ3ZWIiLCJzY29wZSI6WyJhbGwiXX0.ec9rGme8-FyzFn3dgU8SEC1Vb_w6tovAT4hOw2hhtk7YrXD2mmkN8hMCFgFB34ChC-nrtiFhzU6Ay_OxbnWfQ2Tp7Un35Q3LhaHFG8wkzJhkw_KgxQhmVr2RNPJJntesC-NWMckAUNtYJU-mLRjP4qrxbPTmEzMuxFTAofAgVuiF4oKcn5fMIUU4g9w6bUJ_CbJ57CYSpkUiRyAtseunUw-YD2Q0jaBRvE-IVP4SFc21BJUiT6_mmJV3_L7ttsZPfWmV26gWLoaOXfEIrHTPiYgg7pmHCgEp8TJMbuYR4R51v9uJte5k2dpp1ckQp900US11ObsLSL93Tk982AdcQQ");

    }
}
